package com.itjianren.employeemanagementsystem.controller;

import com.itjianren.employeemanagementsystem.dto.EmployeeQueryDTO;
import com.itjianren.employeemanagementsystem.dto.PageResult;
import com.itjianren.employeemanagementsystem.model.Employee;
import com.itjianren.employeemanagementsystem.model.User;
import com.itjianren.employeemanagementsystem.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * 员工管理控制器
 */
@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工列表页（默认查询第一页）
     */
    @GetMapping
    public String list(Model model, HttpSession session,
                       @RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize) {
        // 登录校验（已登录用户才能访问）
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }

        // 默认查询（无筛选条件时分页展示）
        EmployeeQueryDTO queryDTO = new EmployeeQueryDTO();
        queryDTO.setOffset((pageNum - 1) * pageSize); // 计算分页偏移量
        queryDTO.setPageSize(pageSize);
        PageResult<Employee> pageResult = employeeService.findByCondition(queryDTO);

        // 传递数据到页面
        model.addAttribute("pageResult", pageResult);
        model.addAttribute("pageNum", pageNum); // 当前页码，用于分页组件
        model.addAttribute("queryDTO", queryDTO); // 回显查询条件
        return "employee/list";
    }

    /**
     * 跳转添加员工页面
     */
    @GetMapping("/add")
    public String addPage(Model model) {
        // 传递空对象用于表单绑定，避免页面报错
        model.addAttribute("employee", new Employee());
        return "employee/add";
    }

    /**
     * 保存新增员工
     */
    @PostMapping("/add")
    public String add(@Validated Employee employee,
                      BindingResult result,
                      HttpSession session,
                      RedirectAttributes redirectAttributes) {
        // 校验参数合法性
        if (result.hasErrors()) {
            return "employee/add";
        }

        // 设置创建人（当前登录用户）
        User loginUser = (User) session.getAttribute("user");
        employee.setCreatedBy(loginUser.getId());

        // 保存员工信息
        try {
            employeeService.insert(employee);
            redirectAttributes.addFlashAttribute("message", "添加员工成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "添加员工失败：" + e.getMessage());
            return "redirect:/employee/add";
        }

        return "redirect:/employee";
    }

    /**
     * 跳转编辑员工页面
     */
    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Integer id, Model model, RedirectAttributes redirectAttributes) {
        try {
            Employee employee = employeeService.findById(id);
            if (employee == null) {
                redirectAttributes.addFlashAttribute("error", "员工不存在或已被删除！");
                return "redirect:/employee";
            }
            model.addAttribute("employee", employee);
            return "employee/edit";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "加载员工信息失败：" + e.getMessage());
            return "redirect:/employee";
        }
    }

    /**
     * 更新员工信息
     */
    @PostMapping("/edit")
    public String edit(@Validated Employee employee,
                       BindingResult result,
                       RedirectAttributes redirectAttributes) {
        // 校验参数
        if (result.hasErrors()) {
            return "employee/edit";
        }

        // 执行更新
        try {
            employeeService.update(employee);
            redirectAttributes.addFlashAttribute("message", "更新员工成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "更新员工失败：" + e.getMessage());
            return "redirect:/employee/edit/" + employee.getId();
        }

        return "redirect:/employee";
    }

    /**
     * 删除员工
     */
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        try {
            // 校验员工是否存在
            Employee employee = employeeService.findById(id);
            if (employee == null) {
                redirectAttributes.addFlashAttribute("error", "员工不存在，删除失败！");
                return "redirect:/employee";
            }
            // 执行删除
            employeeService.delete(id);
            redirectAttributes.addFlashAttribute("message", "删除员工成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除员工失败：" + e.getMessage());
        }
        return "redirect:/employee";
    }

    /**
     * 查看员工详情
     */
    @GetMapping("/view/{id}")
    public String view(@PathVariable Integer id, Model model, RedirectAttributes redirectAttributes) {
        try {
            Employee employee = employeeService.findById(id);
            if (employee == null) {
                redirectAttributes.addFlashAttribute("error", "员工不存在或已被删除！");
                return "redirect:/employee";
            }
            model.addAttribute("employee", employee);
            return "employee/view";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "查看员工详情失败：" + e.getMessage());
            return "redirect:/employee";
        }
    }

    /**
     * 员工筛选查询（带分页）
     */
    @PostMapping("/search")
    public String search(@ModelAttribute EmployeeQueryDTO queryDTO,
                         @RequestParam(defaultValue = "1") Integer pageNum,
                         @RequestParam(defaultValue = "10") Integer pageSize,
                         Model model) {
        // 处理分页参数
        queryDTO.setOffset((pageNum - 1) * pageSize);
        queryDTO.setPageSize(pageSize);

        // 处理模糊查询（去除首尾空格）
        if (queryDTO.getName() != null) {
            queryDTO.setName(StringUtils.trimWhitespace(queryDTO.getName()));
        }
        if (queryDTO.getDepartment() != null) {
            queryDTO.setDepartment(StringUtils.trimWhitespace(queryDTO.getDepartment()));
        }

        // 执行查询
        PageResult<Employee> pageResult = employeeService.findByCondition(queryDTO);

        // 传递数据到页面
        model.addAttribute("pageResult", pageResult);
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("queryDTO", queryDTO); // 回显查询条件
        return "employee/list";
    }
}